const express = require('express');
const bcrypt = require('bcrypt');
const jwt = require('jsonwebtoken');

const { jwtSecret } = require('../config/setting')
const { Student } = require('../models/index')

const router = express.Router();

/**
 * 注册接口
 * 。。。
 */
router.post('/register', async (req, res) => {
    const { id } = req.body;

    const user = await Student.update({password: bcrypt.hashSync('123456', 10)}, { where: { stu_id: id }});

    console.log(user);

    res.send('ok')
})

/**
 * 登录接口
 * request: username and password
 * response: {user info, token}
 */
router.post('/login', async function(req, res) {
    const { username, password } = req.body;

    const user = await Student.findOne({where: { stu_id: username }});

    if (!user){
        return res.status(422).send('not found user')
    }

    const isPasswordValid = bcrypt.compareSync(password, user.password);

    if (!isPasswordValid){
        return res.status(422).send('username or password filed')
    }

    const token = jwt.sign({
        id: user.stu_id
    }, jwtSecret)

    res.send({ user, token });
});

/**
 * get用户信息接口
 * request: headers.authorization
 * response: {user profile}
 */
router.get('/profile', async (req, res) => {
    // examples: Bearer eyJhbGciOiJ...
    // 截取空格后的内容
    const token = String(req.headers.authorization).split(' ').pop();

    // token转化为id
    let id = 0;
    try {
        const jwtData = jwt.verify(token, jwtSecret);
        id = jwtData.id;
    }catch (e) {
        console.log('token err: JsonWebTokenError: invalid signature');
        return res.status(422).send('Login expired')
    }

    // 通过id获取用户
    const user = await Student.findOne({ where: {stu_id: id }});

    // 未找到token对应user
    if (!user){
        return res.status(422).send('Not logged in')
    }

    res.send({ user })
})

router.get('/', async function (req, res, next) {
    // const clzs = await Class.findAll();
    // res.send(clzs);

    // const class_course = await ClassCourse.findAll()
    // res.send(class_course)

    // const course = await Course.findAll();
    // res.send(course)

    // const college = await College.findAll();
    // res.send(college)

    // const teacher = await Teacher.findAll();
    // res.send(teacher)

    // const student = await Student.findAll();
    // res.send(student)

    res.send('ok')
});

module.exports = router;
